package utils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: Administrator
 * @date: 2021/05/11 9:29
 * @description:自动更新工具类
 */
public class UpdateUtil {

    private static final Pattern PING_PATTERN = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)",    Pattern.CASE_INSENSITIVE);

    /**
     * 功能描述: <br>
     * 〈ping命令封装〉
     * @Param: [ipAddress, pingTimes, timeOut]
     * @Return: boolean
     * @Author: Administrator
     * @Date: 2021/05/11 10:01
     */
    public static boolean isOnline(String ipAddress,int pingTimes,int timeOut){
        String pingCommand = "ping " + ipAddress + " -n " + pingTimes    + " -w " + timeOut;
        String result = "";
        InputStream inputStream = null;
        Runtime runtime = Runtime.getRuntime();

        try {
            Process exec = runtime.exec(pingCommand);
            if(exec==null){
                return false;
            }
            inputStream = exec.getInputStream();
            result = CommonUtil.getStringFromInputStream(inputStream,Charset.forName("GB2312"));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(getCheckResult(result)==1){
            return true;
        }
        return false;
    }


    /**
     * 功能描述: <br>
     * 〈若line含有=18ms TTL=16字样,说明已经ping通,返回1,否則返回0.〉
     * @Param: [line]
     * @Return: int
     * @Author: Administrator
     * @Date: 2021/05/11 10:02
     */
    private  static  int getCheckResult(String line) {
        Matcher matcher = PING_PATTERN.matcher(line);
        while (matcher.find()) {
            return 1;
        }
        return 0;
    }
}
